package com.xxl.job.executor.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class IpUtil {

    public static String getLocalIp() {
        String ip = "127.0.0.1"; // 默认值
        try {
            ProcessBuilder builder = new ProcessBuilder("ifconfig");
            Process process = builder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            boolean enInterface = false;

            while ((line = reader.readLine()) != null) {
                line = line.trim();

                // 检查网卡是否以 'en' 开头
                if (line.startsWith("en")) {
                    enInterface = true;  // 标记为找到以 'en' 开头的网卡
                }

                // 获取对应网卡的 inet 地址
                if (enInterface && line.contains("inet") && !line.contains("inet6")) {
                    String[] parts = line.split("\\s+");
                    ip = parts[1];  // 提取IP地址
                    break;
                }
            }

            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ip;
    }
}
